var WorkProcedureBoard = function () {
  var template = /* html */ `
    <div class="work-procedure-board" v-loading.fullscreen.lock="loading">
      <template v-if="isShow">
      <search-btns ref="searchBtns" :has-search="true" search-btn-text="查询" :popover-width="325" search-title="查询条件"
        @after-leave="afterLeave" v-if="search!==null">
        <div slot="search">
          <el-select v-if="deptWorkName===null" clearable filterable v-model="search.workshopId" size="small" placeholder="车间" style="width:150px">
            <el-option v-for="item in workshopList" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
          <span v-else style="margin-right:20px">部门-车间：{{deptWorkName}}</span>
          <el-date-picker v-model="search.month" :clearable="false" :editable="false" type="month" size="small" style="width:110px">
          </el-date-picker>

          <el-button size="small" type="primary" @click="searchData">查询</el-button>
        </div>
      </search-btns>
      <template v-if="workProData!==null">
        <div ref="boardContent" class="work-procedure-board-list" :key="boardId">
          <div class="procedure-board-pro">
            <work-process-table ref="workTable" :work-pro-data="workProData"></work-process-table>
          </div>
          <div class="procedure-board-machine">
            <machine-process-table ref="machineTable" :machine-pro-data="workProData"></machine-process-table>
          </div>
        </div>
      </template>
      <div v-else-if="search===null" class="no-data" style="color:#ffffff">
        未设置车间，无法查询到产能数据
      </div>
      </template>
    </div>
  `;

  return {
    mixins: [
      boardRunningMixin,
      boardMixin()
    ],

    provide: function () {
      return {
        workProcedureBoard: this
      };
    },

    data: function () {
      return {
        loading: false,
        isShow: false,
        workProData: null,
        resizeCount: 0,
        workshopList: [],
        search: null,
        oldSearch: null,
        boardId: SysUtil.getId()
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setUser(),
        this.getServiceTime()
      ]).then(function (res) {
        var workshopId = res[0];
        if (workshopId === null) {
          self.loading = false;
          self.isShow = true;
          self.search = null;
          self.workProData = null;
          return;
        }

        var month = res[1];
        var search = {
          workshopId: workshopId,
          month: month
        };
        self.search = _.cloneDeep(search);
        self.oldSearch = _.cloneDeep(search);
        self.setProData().then(function (workProData) {
          var workshopList = workProData.getWorkshopList();
          workProData.toSearchData(search);

          self.workshopList = workshopList;
          self.oldSearch = _.cloneDeep(self.search);

          self.boardRunning();
          self.loading = false;
          self.isShow = true;
        });
      }).catch(function () {
        self.loading = false;
        self.isShow = true;
      });
    },

    methods: {
      setUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          var deptWork;
          var permissionList = user.permissionList;
          var isManager = user.isManager;
          if (permissionList.indexOf('/superManager') !== -1) {
            isManager = 1;
          }

          var hasSelect = isManager === 1 || user.duty === '1';
          if (hasSelect) {
            return '';
          }
          var deptId = user.deptId;
          if (SysUtil.isEmpty(deptId) || deptId === '0') {
            return null;
          }
          deptWork = [`dept-${deptId}`];
          var workShopId = user.workShopId;
          if (!SysUtil.isEmpty(workShopId) && workShopId !== '0') {
            deptWork.push(`workshop-${workShopId}`);
          } else {
            return null;
          }

          return self.setDeptWorkName(deptWork, user).then(function () {
            return workShopId;
          });
        });
      },

      setProData: function () {
        var self = this;
        return Promise.all([
          self.setWorkProData(),
          self.setMachineProData()
        ]).then(function (res) {
          var data = {
            workProList: res[0],
            machineProList: res[1]
          };
          var search = self.search;

          var workProData = self.workProData;
          if (workProData === null) {
            workProData = new WorkProcedureInfo(data, search.month);
            self.workProData = workProData;
          } else {
            workProData.resetProData(data, search.month);
          }
          return workProData;
        });
      },

      setWorkProData: function () {
        var month = this.search.month;
        month = moment(month).format('YYYY-MM');
        return ajaxRequest('displayView/queryMacineCapacity', {
          month: month
        }).then(function (capacityList) {
          return capacityList;
        });
      },

      setMachineProData: function () {
        var month = this.search.month;
        month = moment(month).format('YYYY-MM');
        return ajaxRequest('displayView/getMachieProcessCapacity', {
          month: month
        }).then(function (capacityList) {
          return capacityList;
        });
      },

      getServiceTime: function () {
        return ajaxRequest('displayView/getDate', {}, true, false).then(function (time) {
          return moment(time).valueOf();
        }).catch(function () {
          return moment().valueOf();
        });
      },

      searchData: function () {
        var search = this.search;
        var oldSearch = this.oldSearch;

        var self = this;
        this.clearTimeoutList();
        this.loading = true;
        if (!moment(search.month).isSame(oldSearch.month)) {
          this.setProData().then(function (workProData) {
            self.$refs['searchBtns'].closePopover();
            workProData.toSearchData(search);
            self.oldSearch = _.cloneDeep(search);
            self.boardId = SysUtil.getId();
            self.boardRunning();
            self.loading = false;
          }).catch(function () {
            self.loading = false;
          });
          return;
        }

        setTimeout(function () {
          self.$refs['searchBtns'].closePopover();
          self.workProData.toSearchData(search);
          self.oldSearch = _.cloneDeep(search);
          self.boardId = SysUtil.getId();
          self.boardRunning();
          self.loading = false;
        }, 500);
      },

      afterLeave: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      boardRunning: function () {
        this.clearTimeoutList();

        this.resetWorkProDataRunning();
        this.tableRunning();
      },

      resetWorkProDataRunning: function () {
        var tomorrowMoment = moment().add(1, 'day').startOf('day');
        var delayTime = tomorrowMoment.diff(moment());
        delayTime = Math.min(delayTime, 15 * 60 * 1000);

        var self = this;
        var timeout = setTimeout(function () {
          self.setProData().then(function (workProData) {
            var search = self.search;
            var workshopList = workProData.getWorkshopList();
            var obj = _.find(workshopList, {
              id: search.workshopId
            });
            if (obj === undefined) {
              search.workshopId = '';
              self.oldSearch = _.cloneDeep(self.search);
            }
            workProData.toSearchData(search);
            self.workshopList = workshopList;

            self.resetWorkProDataRunning();
          });
          self.timeoutList[0] = null;
        }, delayTime);
        this.timeoutList[0] = timeout;
      },

      resetTableRunning() {
        this.resizeCount++;
        if (this.clickCount < 2) {
          return;
        }
        this.resizeCount = 0;
        this.tableRunning();
      },

      tableRunning: function () {
        var self = this;
        var timeout = setTimeout(function () {
          self.$refs['workTable'].tableRunning();
          self.$refs['machineTable'].tableRunning();
          self.timeoutList[1] = null;
          self.tableRunning();
        }, 5000);
        this.timeoutList[1] = timeout;
      },

      checkHasScroll: function () {
        var content = this.$refs['boardContent'];
        var height = $(content).outerHeight(true);
        var totalHeight = $(this.$el).height();
        return totalHeight < height;
      }
    },

    components: {
      SearchBtns: SearchBtns,
      WorkProcessTable: WorkProcessTable,
      MachineProcessTable: MachineProcessTable
    },

    template: template
  };
}();
